package com.sky.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.*;
import com.sky.websocketserver.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.el.stream.Stream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 梁科
 * @Version 1.0
 * @ Date 2025/10/28 23:38
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private AddressBookMapper addressBookMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private WebSocketServer webSocketServer;

    /**
     * 通过读取配置文件注入店铺地址信息
     */
    @Value(value = "${sky.shop.address}")
    private String shopAddress;
    /**
     * 读取配置文件注入百度地图需要的ak信息
     */
    @Value(value = "${sky.baidu.ak}")
    private String ak;

    /**
     * 用户端提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 1. 检查地址簿是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 2. 检查购物车是否为空
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.show(userId);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 判断是否超出配送距离
        checkOutOfRange(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        // 3. 插入一条order表数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(userId);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orderMapper.insert(orders);
        // 该集合用于批量插入order_detail表
        List<OrderDetail> orderDetails = new ArrayList<>();
        // 4. 插入n条order_detail表数据
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.batchInsert(orderDetails);
        // 5. 删除该用户的购物车表信息
        shoppingCartMapper.cleanByUserId(userId);
        // 6. 封装OrderSubmitVO对象进行返回
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        return orderSubmitVO;
    }

    /**
     * 订单支付成功
     *
     * @param ordersPaymentDTO
     */
    @Override
    public void paySuccess(OrdersPaymentDTO ordersPaymentDTO) {
        // 订单支付成功后，修改订单表中的数据
        // 1. 根据订单号查询订单
        Orders orders = orderMapper.getByorderNumber(ordersPaymentDTO.getOrderNumber());
        log.info("orders = {}", orders);
        // 2. 根据订单id修改订单信息
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(ordersPaymentDTO.getPayMethod());
        orderMapper.update(orders);

        // 付款成功后使用websocket与前端建立长连接，推送来单提醒信息
        // 先将需要传给前端的信息封装到map中，然后直接将map转换为json字符串再发给前端即可！！！
        /*
        <!--该依赖可以将java对象转换为json字符串（通常是将信息先封装到Map中，然后将map转换为json字符串）-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
         */
        Map<String, Object> map = new HashMap<>();
        // 规定type=1表示来单提醒，type=2表示客户催单
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    /**
     * 分页查询历史订单
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQueryHistoryOrder(Integer page, Integer pageSize, Integer status) {
        // 开启分页查询
        PageHelper.startPage(page, pageSize);
        // 根据userId + status 进行分页查询
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        ordersPageQueryDTO.setStatus(status);
        Page<Orders> pageOrders = orderMapper.pageQuery(ordersPageQueryDTO);
        // 用于封装数据返回结果
        List<OrderVO> list = new ArrayList<>();
        for (Orders pageOrder : pageOrders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(pageOrder, orderVO);
            Long id = pageOrder.getId();
            // 根据订单id查找订单明细
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
            orderVO.setOrderDetailList(orderDetails);
            list.add(orderVO);
        }
        return new PageResult(pageOrders.getTotal(), list);
    }

    /**
     * 根据订单id查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetailByOrderId(Long id) {
        // 根据订单id查找订单信息
        Orders orders = orderMapper.getByOrderId(id);
        // 用于封装给前端返回的数据
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void getOneAgain(Long id) {
        Long userId = BaseContext.getCurrentId();
        // 业务流程：将该订单的订单详情重新加入到购物车中
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        // 用于封装购物车对象，插入数据库表
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCarts.add(shoppingCart);
        }
        shoppingCartMapper.bantchInsert(shoppingCarts);
    }

    /**
     * 管理端订单条件分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryOnAdmin(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 用于封装数据返回给前端
        List<OrderVO> list = new ArrayList<>();
        // 开始分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        for (Orders orders : ordersPage) {
            OrderVO orderVO = new OrderVO();
            // 将javabean转换为VO
            BeanUtils.copyProperties(orders, orderVO);
            Long id = orders.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
            // todo 将菜品信息拼接为字符串
            String orderDishes = "";
            for (OrderDetail orderDetail : orderDetails) {
                orderDishes += orderDetail.getName() + "*" + orderDetail.getNumber();
            }
            orderVO.setOrderDishes(orderDishes);
            list.add(orderVO);
        }
        PageResult pageResult = new PageResult(ordersPage.getTotal(), list);
        return pageResult;
    }

    /**
     * 获取各个状态的订单数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO getOrderStatistics() {
        // 获取待接单数量
        Integer toBeConfirmed = orderMapper.getToBeConfirmed();
        // 获取待派送数量
        Integer confirmed = orderMapper.getConfirmed();
        // 获取派送中数量
        Integer deliveryInProgress = orderMapper.getDeliveryInProgress();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(ordersConfirmDTO.getId());
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        orders.setId(ordersRejectionDTO.getId());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        // 退款逻辑暂时跳过去
        orderMapper.update(orders);
    }

    /**
     * 管理端取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        // 退款逻辑暂时跳过
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 用户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        // 判断订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverReport(LocalDate begin, LocalDate end) {
        // 存放日期序列
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放每天对应的营业额
        List<Double> numberList = new ArrayList<>();
        // 遍历日期集合，取出每一天的已完成订单的营业额
        for (LocalDate date : dateList) {
            // 每天的开始时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 每天的结束时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 已完成的订单
            Integer status = Orders.COMPLETED;
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", status);
            Double amount = orderMapper.getAmount(map);
            // 防止查询营业额为0时，amount为null造成数据错误
            if (amount == null) {
                amount = 0.0;
            }
            numberList.add(amount);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        // 存放日期序列
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 存放每天对应的订单总数
        List<Integer> orderCountList = new ArrayList<>();
        // 存放每天对应的有效订单总数
        List<Integer> validOrderCountList = new ArrayList<>();
        // 遍历每天的日期
        for (LocalDate date : dateList) {
            // 每天的开始时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 每天的结束时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            // 查询当天的所有订单
            Integer orderCount = orderMapper.getOrderCount(map);
            if (orderCount == null) {
                orderCount = 0;
            }
            orderCountList.add(orderCount);
            map.put("status", Orders.COMPLETED);
            // 查询当天的所有有效订单
            Integer validOrderCount = orderMapper.getOrderCount(map);
            if (validOrderCount == null) {
                validOrderCount = 0;
            }
            validOrderCountList.add(validOrderCount);
        }
        // 获取总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        // 获取总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        // 计算订单完成率
        Double orderCompletionRate = Double.valueOf(validOrderCount) / totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 商品销量top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO salesTop10Report(LocalDate begin, LocalDate end) {
        // 使用map封装查询条件
        Map map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", Orders.COMPLETED);
        // List<name + number>
        List<GoodsSalesDTO> goodsSalesDTO = orderMapper.getTop10(map);
        List<String> nameList = goodsSalesDTO.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }
}
